<template>
  <t-modal
    title="扩展属性"
    width="900px"
    :visible="visible"
    @cancel="closeModal()"
    wrapClassName="add-extend-attribute-container"
    v-bind="footer"
    forceRender
  >
    <div class="curve-modal-body">
      <div class="type-container">
        <div class="add-btn-container" @click="handelAddType()">
          <a-icon type="plus" />新建分类
        </div>
        <div class="list-item-container">
          <a-empty :description="false" v-if="groupsSoucre.length == 0" />
          <div
            class="type-item"
            :class="[activeIndex == index && 'active']"
            v-for="(item, index) in groupsSoucre"
            :key="index"
            @click="handelCheckGroup(item, index)"
          >
            <div class="name">
              <a-icon type="pushpin" />
              {{ item.extendParamGroupName }}
            </div>
            <div class="operate">
              <a-tooltip placement="top">
                <template slot="title">
                  <span>编辑</span>
                </template>
                <a-icon type="edit" @click.stop="handelEditType(item)" />
              </a-tooltip>
              <a-tooltip placement="top">
                <template slot="title">
                  <span>删除</span>
                </template>
                <a-icon type="delete" @click.stop="handelDeleteType(item)" />
              </a-tooltip>
            </div>
          </div>
        </div>
      </div>
      <div class="table-container">
        <div class="main">
          <vxe-table
            ref="xTable"
            height="99%"
            align="center"
            border="inner"
            size="small"
            show-overflow
            show-header-overflow
            :data="tableData"
            :column-config="{ resizable: true }"
            :loading="loading"
            keep-source
          >
            <vxe-column title="属性名称">
              <template #default="{ row }">
                <a-input
                  :class="[row.isCheck && 'error']"
                  v-if="row.isSave"
                  v-model="row.extendParamName"
                  placeholder="请输入"
                  @change="changeExtendParamName($event, row)"
                ></a-input>
                <span v-else>{{ row.extendParamName }}</span>
              </template>
            </vxe-column>
            <vxe-column title="属性值">
              <template #default="{ row }">
                <a-input
                  v-if="row.isSave"
                  v-model="row.extendParamValue"
                  placeholder="请输入"
                ></a-input>
                <span v-else>{{ row.extendParamValue }}</span>
              </template>
            </vxe-column>
            <vxe-column title="单位">
              <template #default="{ row }">
                <a-input
                  v-if="row.isSave"
                  v-model="row.extendParamType"
                  placeholder="请输入"
                ></a-input>
                <span v-else>{{ row.extendParamType }}</span>
              </template>
            </vxe-column>
            <vxe-column
              field="operate"
              width="180"
              title="操作"
              fixed="right"
              align="left"
            >
              <template slot-scope="scope">
                <div class="text-button-group">
                  <template v-if="scope.row.isSave">
                    <a-button type="link" @click="saveRowEvent(scope)">
                      保存
                    </a-button>
                    <a-button
                      v-if="scope.row.extendParamId"
                      type="link"
                      class="danger"
                      @click="handelDeleteAttribute(scope)"
                    >
                      删除
                    </a-button>
                    <a-button type="link" @click="cancelRowEvent(scope)">
                      取消
                    </a-button>
                  </template>
                  <template v-else>
                    <a-button type="link" @click="editRowEvent(scope.row)">
                      编辑
                    </a-button>
                    <a-button
                      type="link"
                      class="danger"
                      @click="handelDeleteAttribute(scope)"
                    >
                      删除
                    </a-button>
                  </template>
                </div>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <div class="add-btn-container" @click="handelAddAttribute()">
          <a-icon type="plus" />新建属性
        </div>
      </div>
    </div>

    <!-- 新建分类 -->
    <addExtendTypeModal
      :visible.sync="typeModalVisible"
      :parameter="typeModalSoucre"
      @ok="handelOk"
    ></addExtendTypeModal>
  </t-modal>
</template>

<script>
import {
  getElementExtendParamGroups,
  getElementExtendParams,
  deleteElementExtendParamGroup,
  addElementExtendParams,
  updateElementExtendParam,
  deleteElementExtendParamById,
} from "@/api/bim";
import addExtendTypeModal from "./addExtendTypeModal.vue";
export default {
  components: {
    addExtendTypeModal,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    footer: {
      type: Object,
      default() {
        return {
          footer: null,
        };
      },
    },
  },
  data() {
    return {
      //分类
      groupsSoucre: [],
      checkGroup: {},
      activeIndex: 0,
      typeModalVisible: false,
      typeModalSoucre: {},
      firstRefresh: true,
      //属性
      loading: false,
      tableData: [],
      currentSoucre: {},
    };
  },

  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getGroupsData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    addElementExtendParams,
    updateElementExtendParam,
    handelOk(row) {
      let { data } = row;
      this.typeModalVisible = false;
      this.getGroupsData()
        .then((_) => {
          let { text, extendParamGroupId } = this.typeModalSoucre;
          if (text == "新增") {
            this.checkGroup = data.data;
            this.activeIndex = this.groupsSoucre.length - 1;
          } else {
            this.checkGroup.extendParamGroupId = extendParamGroupId;
          }
          this.getTableData();
        })
        .catch((_) => {});
    },
    //新建分类
    handelAddType() {
      let { probeRet } = this.$parent;
      this.typeModalSoucre = {
        text: "新建",
        dataSetId: probeRet.dataSetId,
        elemId: probeRet.elemId,
      };
      this.firstRefresh = false;
      this.typeModalVisible = true;
    },
    //编辑分类
    handelEditType(row) {
      let { probeRet } = this.$parent;
      this.typeModalSoucre = {
        text: "编辑",
        dataSetId: probeRet.dataSetId,
        elemId: row.elementIntId,
        extendParamGroupId: row.extendParamGroupId,
        extendParamGroupName: row.extendParamGroupName,
      };
      this.typeModalVisible = true;
      this.firstRefresh = false;
    },
    //删除分类
    handelDeleteType(row) {
      let that = this;
      that.$confirm({
        title: "提示",
        content: "删除属性分类后，该分类下所有属性都将被删除，确定继续删除吗？",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          let { dataSetId, elemId } = that.$parent.probeRet;
          deleteElementExtendParamGroup({
            dataSetId,
            elementIntId: elemId,
            extendParamGroupId: row.extendParamGroupId,
          })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                that.activeIndex = 0;
                that.getGroupsData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },
    handelCheckGroup(item, index) {
      this.activeIndex = index;
      this.checkGroup = item;
      this.getTableData();
    },
    //查询分类
    getGroupsData() {
      return new Promise((resolve, reject) => {
        let { dataSetId, elemId } = this.$parent.probeRet;
        getElementExtendParamGroups({
          dataSetId,
          elementIntId: elemId,
        })
          .then((res) => {
            this.groupsSoucre = res?.data?.data ?? [];
            if (this.firstRefresh) {
              this.checkGroup = this.groupsSoucre?.[0] ?? {};
              this.getTableData();
            }
            resolve();
          })
          .catch((_) => {
            this.checkGroup = {};
            this.groupsSoucre = [];
            reject();
          });
      });
    },
    //查询列表
    getTableData() {
      return new Promise((resolve, reject) => {
        let { dataSetId, elemId } = this.$parent.probeRet;
        let { extendParamGroupId } = this.checkGroup;
        if (!extendParamGroupId) {
          return;
        }
        this.loading = true;
        getElementExtendParams({
          elementIntId: elemId,
          dataSetId,
          extendParamGroupId,
        })
          .then((res) => {
            let { data } = res;
            let soucre = data?.data?.[0]?.data ?? [];
            soucre.forEach((item) => {
              this.$set(item, "uuid", this._getUUID(32, 32));
              this.$set(item, "isSave", false);
            });
            this.tableData = soucre;
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },
    //删除属性
    handelDeleteAttribute(scope) {
      let { row, $rowIndex } = scope;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          let { dataSetId } = that.$parent.probeRet;
          deleteElementExtendParamById({
            dataSetId,
            extendParamGroupId: row.extendParamGroupId,
            extendParamId: row.extendParamId,
          })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                if (res.data.errMsg) {
                  that.$message.error(res.data.errMsg);
                } else {
                  that.tableData.splice($rowIndex, 1);
                  that.$message.success("删除成功", 1.5);
                }
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },
    //新增属性
    handelAddAttribute() {
      let { elementIntId, extendParamGroupId } = this.checkGroup;
      this.tableData.push({
        elementIntId,
        extendParamGroupId,
        extendParamName: "",
        extendParamValue: "",
        extendParamType: "",
        isSave: true,
        isCheck: false,
      });
    },
    //新增-保存
    saveRowEvent(scope) {
      let { row, $rowIndex } = scope;
      return new Promise((resolve, reject) => {
        let { dataSetId } = this.$parent.probeRet;
        let formJson = {
          dataSetId,
        };
        let path = "";
        if (row.extendParamName == "") {
          this.tableData[$rowIndex].isCheck = true;
          return this.$message.warning("属性名称不能为空");
        }
        //编辑
        if (row.extendParamId) {
          path = "updateElementExtendParam";
          formJson.extendParam = {
            extendParamId: row.extendParamId,
            elementGuidId: row.elementGuidId,
            elementName: row.elementName,
            extendParamGroupName: row.extendParamGroupName,
            hostFileId: row.hostFileId,
            extendParamOrder: row.extendParamOrder,
            elementIntId: row.elementIntId,
            extendParamGroupId: row.extendParamGroupId,
            extendParamName: row.extendParamName,
            extendParamValue: row.extendParamValue,
            extendParamType: row.extendParamType,
          };
        } else {
          //新增
          path = "addElementExtendParams";
          formJson.extendParams = [
            {
              elementIntId: row.elementIntId,
              extendParamGroupId: row.extendParamGroupId,
              extendParamName: row.extendParamName,
              extendParamValue: row.extendParamValue,
              extendParamType: row.extendParamType,
            },
          ];
        }
        this[path](formJson)
          .then((res) => {
            if (res.statusCode === 200 || res === 1) {
              if (res.data.errMsg) {
                this.$message.warning(res.data.errMsg, 1.5);
              } else {
                let soucre = res.data.data?.[0] ?? {};
                this.$message.success("保存成功", 1.5);
                this.tableData[$rowIndex].isSave = false;
                this.tableData[$rowIndex].isCheck = false;
                this.tableData[$rowIndex].extendParamId = soucre.extendParamId;
                this.tableData[$rowIndex].elementGuidId = soucre.elementGuidId;
                this.tableData[$rowIndex].elementName = soucre.elementName;
                this.tableData[$rowIndex].extendParamGroupName =
                  soucre.extendParamGroupName;
                this.tableData[$rowIndex].hostFileId = soucre.hostFileId;
                this.tableData[$rowIndex].extendParamOrder =
                  soucre.extendParamOrder;
                this.tableData[$rowIndex].elementIntId = soucre.elementIntId;
                this.tableData[$rowIndex].extendParamGroupId =
                  soucre.extendParamGroupId;
                this.tableData[$rowIndex].extendParamName =
                  soucre.extendParamName;
                this.tableData[$rowIndex].extendParamValue =
                  soucre.extendParamValue;
                this.tableData[$rowIndex].extendParamType =
                  soucre.extendParamType;
              }
            } else {
              this.$message.error(res?.message ?? "保存失败");
            }
            resolve();
          })
          .catch((_) => {
            reject();
          });
      });
    },

    //取消
    cancelRowEvent(scope) {
      let { $rowIndex, row } = scope;
      let { extendParamId } = row;
      if (extendParamId) {
        row.extendParamName = this.currentSoucre.extendParamName;
        row.extendParamValue = this.currentSoucre.extendParamValue;
        row.extendParamType = this.currentSoucre.extendParamType;
        row.isSave = false;
      } else {
        this.tableData.splice($rowIndex, 1);
      }
    },
    //编辑
    editRowEvent(row) {
      this.currentSoucre = {
        extendParamName: row.extendParamName,
        extendParamValue: row.extendParamValue,
        extendParamType: row.extendParamType,
      };
      row.isSave = true;
    },

    changeExtendParamName(e, row) {
      row.isCheck = false;
    },

    closeModal() {
      this.$emit("update:visible", false);
      this.groupsSoucre = [];
      this.checkGroup = {};
      this.activeIndex = 0;
      this.typeModalVisible = false;
      this.typeModalSoucre = {};
      this.firstRefresh = true;
      //属性
      this.loading = false;
      this.tableData = [];
      this.currentSoucre = {};
      this.$parent.getExtendData();
    },

    //指定长度和基数
    _getUUID(len, radix) {
      var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(
        ""
      );
      var uuid = [],
        i;
      radix = radix || chars.length;
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
      } else {
        var r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
        uuid[14] = "4";
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | (Math.random() * 16);
            uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
          }
        }
      }
      return uuid.join("");
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-extend-attribute-container {
  .curve-modal-body {
    height: 600px;
    display: flex;
    overflow: hidden;
    .add-btn-container {
      border-radius: 4px 4px 4px 4px;
      border: 1px dashed #1677ff;
      display: flex;
      align-items: center;
      justify-content: center;
      font-family: Microsoft YaHei, Microsoft YaHei;
      font-weight: 400;
      font-size: 14px;
      color: #1677ff;
      letter-spacing: 1px;
      cursor: pointer;
    }
    .type-container {
      width: 240px;
      height: 100%;
      border-radius: 6px 6px 6px 6px;
      border: 1px solid #d9d9d9;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      .add-btn-container {
        height: 32px;
        margin: 10px;
      }
      .list-item-container {
        flex: 1;
        overflow: auto;
        position: relative;
        .ant-empty {
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
        }
        .type-item {
          cursor: pointer;
          box-sizing: border-box;
          padding: 8px 16px 8px 20px;
          height: 32px;
          font-family: Microsoft YaHei, Microsoft YaHei;
          font-weight: 400;
          font-size: 14px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .name {
            color: #333333;
          }
          .operate {
            opacity: 0;
            transition: 0.2s;
            .anticon {
              margin-right: 10px;
              &:last-of-type {
                margin-right: 0;
              }
            }
          }
          &.active {
            background: rgba(22, 119, 255, 0.1);
            .name {
              color: #1677ff;
            }
          }
          &:hover {
            background: rgba(22, 119, 255, 0.1);
            .operate {
              transition: 0.2s;
              opacity: 1;
            }
          }
        }
      }
    }
    .table-container {
      flex-shrink: 0;
      padding-left: 10px;
      flex: 1;
      display: flex;
      flex-direction: column;
      .main {
        flex: 1;
        .error {
          border-color: #ff4d4f;
        }
      }
      .add-btn-container {
        height: 40px;
        margin-top: 4px;
      }
    }
  }
}
</style>
